package services

import (
	admindao "TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/internal/app/dao"
	"TaskAssignmentSystem/pkg/db/mysql"
	"TaskAssignmentSystem/pkg/timehandler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
)

const (
	ZXZ_TEAM_OPEN                        = 1                                      //有效
	ZXZ_TEAM_CLOSE                       = 0                                      //无效
	ZXZ_TEAM_PROFILE_ALL                 = "ZXZ_TEAM_PROFILE_ALL"                 //团队功能（0-关闭，1-开启）
	ZXZ_TEAM_PROFILE_ACTIVITY            = "ZXZ_TEAM_PROFILE_ACTIVITY"            //团队创建活动开启
	ZXZ_TEAM_PROFILE_ACTIVITY_TIME       = "ZXZ_TEAM_PROFILE_ACTIVITY_TIME"       //团队创建活动开启时间
	ZXZ_TEAM_PROFILE_AUTH_PEOPLE         = "ZXZ_TEAM_PROFILE_AUTH_PEOPLE"         //有效人数-完成实名认证（0-关闭，1-开启）
	ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME = "ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME" //有效人数-历史芝草大于等于N （0-关闭，1-开启）
	ZXZ_TEAM_PROFILE                     = "ZXZ_TEAM_PROFILE"                     //团队基本属性
	ZXZ_TEAM_LEVEL                       = "ZXZ_TEAM_LEVEL"                       //团队等级有效人数
	ZXZ_TEAM_PROFILE_CREATE              = "ZXZ_TEAM_PROFILE_CREATE"              //团队自主创建条件：历史芝草大于等于num
	ZXZ_TEAM_PROFILE_CREATE_CONSUME      = "ZXZ_TEAM_PROFILE_CREATE_CONSUME"      //团队创建消耗芝草

	STATUS_NORMAL = 1
	REGIST_URL    = "REGIST_URL" //团队注册链接
)

type TeamService struct {
}

func (t *TeamService) DoEffectiveManpower(id uint, userId, teamNumber string, isEffectiveManpower, isAuthentication int, balance float64) {
	user := dao.SystemUser{}
	user.Id = id
	user.UserId = userId
	user.TeamNumber = teamNumber
	user.IsEffectiveManpower = isEffectiveManpower
	user.Balance = balance
	user.IsAuthentication = isAuthentication
	t.EffectiveManpower(user)
}

// 全量计算有效人力
func (t *TeamService) AllEffectiveManpower() {
	var userServe CommonService[SystemViewUser]
	userServe.Query = map[string]interface{}{"is_effective_manpower": 0}
	userServe.WhereStr = append(userServe.WhereStr, "team_number != 'zxz'")
	if users, err := userServe.SelectList(); err != nil {
		return
	} else {
		for i := 0; i < len(users.Data); i++ {
			t.DoEffectiveManpower(users.Data[i].Id, users.Data[i].UserId, users.Data[i].TeamNumber,
				users.Data[i].IsEffectiveManpower, users.Data[i].IsAuthentication, users.Data[i].Balance)
		}
	}
}

// 全量计算团队等级
func (t *TeamService) AllUpdateEffectiveManpower() {
	var systemTeamDao CommonService[admindao.SystemTeam]
	systemTeamDao.WhereStr = append(systemTeamDao.WhereStr, "team_number != 'zxz'")
	if teams, err := systemTeamDao.SelectList(); err != nil {
		return
	} else {
		var dictServe SystemDictService
		result, err := dictServe.GetValueByType(ZXZ_TEAM_LEVEL)
		if err != nil {
			return
		}
		for i := 0; i < len(teams.Data); i++ {
			//计算团队等级
			newTeamPeople := teams.Data[i].TeamPeople
			level := 0
			for i := 0; i < len(result); i++ {
				levelTemp := result[i].DictNumber
				if newTeamPeople >= levelTemp {
					val, strErr := strconv.Atoi(result[i].DictValue)
					if strErr == nil {
						level = val
					}
				}
			}
			if level > teams.Data[i].Level {
				systemTeamDao.Query = map[string]interface{}{"id": teams.Data[i].Id}
				systemTeamDao.Update(map[string]interface{}{"level": level})
			}
		}
	}
}

// 有效人力计算
func (t *TeamService) EffectiveManpower(user dao.SystemUser) {
	//用户已属于团队有效人力，不参与计算
	if user.IsEffectiveManpower == ZXZ_TEAM_OPEN || user.TeamNumber == "zxz" {
		return
	}
	if user.IsEffectiveManpower == ZXZ_TEAM_OPEN {
		return
	}
	if t.VerifyTeamALLAndACTIVITY() {
		var dictServe SystemDictService
		//实名认证是否开启
		if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_AUTH_PEOPLE); err != nil {
			fmt.Printf("ZXZ_TEAM_PROFILE_AUTH_PEOPLE 字典不存在")
			return
		} else {
			//实名认证开启并且用户未实名
			if data.DictNumber == ZXZ_TEAM_OPEN && user.IsAuthentication != ZXZ_TEAM_OPEN {
				return
			}
		}
		//历史芝曹大于等于预设值
		if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME); err != nil {
			fmt.Printf("ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME 字典不存在")
			return
		} else {
			//历史芝草是否开启
			if data.DictNumber == ZXZ_TEAM_OPEN {
				if val, err := strconv.ParseFloat(data.DictValue, 64); err != nil {
					fmt.Printf("ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME DictValue 不是整数")
					return
				} else {
					//先判断余额，余额不够，在历史芝草
					if val > user.Balance {
						var userBalanceLogService UserBalanceLogService
						historyBalance, _ := userBalanceLogService.GetHistoryBalance(user.UserId)
						fmt.Printf("历史芝草 = %T", historyBalance)
						if val > historyBalance {
							return
						}
					}
				}
			}
		}
		//team有效人力+1
		t.UpdateEffectiveManpower(user.TeamNumber, user.Id)
	}
}

func (t *TeamService) VerifyTeamALL() bool {
	var dictServe SystemDictService
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_ALL); err != nil {
		fmt.Printf("VerifyTeamALL ZXZ_TEAM_PROFILE_ALL 字典不存在 %#v\n", err)
		return false
	} else {
		//团队功能整体关闭
		if data.DictNumber == ZXZ_TEAM_CLOSE {
			return false
		}
	}
	return true
}

// 验证 团队功能 及 团队活动是否开启，且在活动范围内
func (t *TeamService) VerifyTeamALLAndACTIVITY() bool {
	var dictServe SystemDictService
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_ALL); err != nil {
		fmt.Printf("VerifyTeamALLAndACTIVITY ZXZ_TEAM_PROFILE_ALL 字典不存在 %#v\n", err)
		return false
	} else {
		//团队功能整体关闭
		if data.DictNumber == ZXZ_TEAM_CLOSE {
			return false
		}
	}
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_ACTIVITY); err != nil {
		fmt.Printf("VerifyTeamALLAndACTIVITY ZXZ_TEAM_PROFILE_ACTIVITY 字典不存在 %#v\n", err)
		return false
	} else {
		//团队活动功能整体关闭
		if data.DictNumber == ZXZ_TEAM_CLOSE {
			return false
		}
	}

	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_ACTIVITY_TIME); err != nil {
		fmt.Printf("VerifyTeamALLAndACTIVITY ZXZ_TEAM_PROFILE_ACTIVITY_TIME 字典不存在 %#v\n", err)
		return false
	} else {
		nowTime := time.Now()
		startTime, err := time.ParseInLocation(timehandler.FormatLayoutTime, data.DictValue, time.Local)
		//活动时间开始时间大于当前时间，未开始
		if err != nil || nowTime.Before(startTime) {
			return false
		}
		endTime, err := time.ParseInLocation(timehandler.FormatLayoutTime, data.Description, time.Local)
		//当前时间大于活动时间结束时间，已结束
		if err != nil || endTime.Before(nowTime) {
			return false
		}
	}
	return true
}

// team有效人力+1 计算团队等级
func (t *TeamService) UpdateEffectiveManpower(teamNumber string, id uint) error {
	var systemTeamDao dao.Common[admindao.SystemTeam]
	var userServers UserService
	team, err := systemTeamDao.First(map[string]interface{}{"team_number": teamNumber})
	if err != nil && team.Status != 1 {
		userServers.UpdateTeam(id) //团长离职或者团队不存在。用户团队还原zxz
		return errors.New("该团队不存在")
	}
	//user改成有效人力
	userServers.UpdateEffectiveManpower(id)
	//有效人数+1,历史有效人数+1
	systemTeamDao.Query = map[string]interface{}{"id": team.Id}
	systemTeamDao.Update(map[string]interface{}{
		"team_people":         gorm.Expr("team_people + ?", 1),
		"team_people_history": gorm.Expr("team_people_history + ?", 1)})
	//计算团队等级
	var dictServe SystemDictService
	if result, err := dictServe.GetValueByType(ZXZ_TEAM_LEVEL); err != nil {
		return errors.New("ZXZ_TEAM_LEVEL 字典不存在")
	} else {
		newTeamPeople := team.TeamPeople + 1
		level := 0
		for i := 0; i < len(result); i++ {
			levelTemp := result[i].DictNumber
			if newTeamPeople >= levelTemp {
				val, strErr := strconv.Atoi(result[i].DictValue)
				if strErr == nil {
					level = val
				}
			}
		}
		if level > team.Level {
			systemTeamDao.Query = map[string]interface{}{"id": team.Id}
			systemTeamDao.Update(map[string]interface{}{"level": level})
		}
	}
	return nil
}

// 创建团队
func (t *TeamService) CreateTeam(userId string) error {
	fmt.Printf("CreateTeam userId %s", userId)
	if !t.VerifyTeamALLAndACTIVITY() {
		return errors.New("团队创建活动未满足。")
	}
	//用户认证
	var systemUserDao dao.Common[dao.SystemUser]
	user, err := systemUserDao.First(map[string]interface{}{"user_id": userId})
	/*  创建团队不需要实名认证
	if user.IsAuthentication == ZXZ_TEAM_CLOSE {
		return errors.New("该账户未实名认证")
	}
	*/
	if err != nil {
		return errors.New("该账户不存在")
	}
	var dictServe SystemDictService
	//团队自主创建条件：历史芝草大于等于num
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_CREATE); err != nil {
		return errors.New("ZXZ_TEAM_PROFILE_CREATE 字典不存在")
	} else {
		//先判断余额，余额不够，在历史芝草
		if data.DictNumber > int(user.Balance) {
			var userBalanceLogService UserBalanceLogService
			historyBalance, _ := userBalanceLogService.GetHistoryBalance(userId)
			fmt.Printf("历史芝草 = %T", historyBalance)
			if data.DictNumber > int(historyBalance) {
				return errors.New("累计获得芝草不满足创建要求")
			}
		}
	}
	//创建团队消耗芝草
	var balanceConsume int
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_CREATE_CONSUME); err != nil {
		return errors.New("ZXZ_TEAM_PROFILE_CREATE_CONSUME 字典不存在")
	} else {
		balanceConsume = data.DictNumber
		if int(user.Balance) < data.DictNumber {
			return errors.New(fmt.Sprintf("芝草不足 %d, 请获得足够芝草后再来", data.DictNumber))
		}
	}
	var systemTeamDao dao.Common[admindao.SystemTeam]
	team, err := systemTeamDao.First(map[string]interface{}{"user_id": userId})
	if err == nil {
		return errors.New(fmt.Sprintf("用户已有团队[%s],无法重复创建。", team.TeamNumber))
	}
	var record admindao.SystemTeam
	record.TeamNumber, _ = dictServe.GetNextTeamNumber()
	record.UserId = userId
	record.UserName = user.RealName
	record.NickName = user.NickName
	record.Level = 0
	record.TeamPeople = 0
	record.TeamPeopleHistory = 0
	record.TeamIncome = 0
	record.TeamPermissions = ""
	record.Status = 1
	if err := systemTeamDao.CreateOne(record).Error; err != nil {
		return err
	}
	//减少用户芝草
	systemUserDao.Query = map[string]interface{}{"user_id": userId}
	systemUserDao.Update(map[string]interface{}{
		"balance": gorm.Expr("balance - ?", balanceConsume)})
	var balanceLogDao dao.Common[admindao.SystemUserBalanceLog]
	var balanceLog admindao.SystemUserBalanceLog
	balanceLog.UserId = userId
	balanceLog.TeamNumber = record.TeamNumber
	balanceLog.LogType = BalanceLogLogTypeIn
	balanceLog.BusinessType = BalanceLogBusinessTypeCreateTeam
	balanceLog.Amount = float64(balanceConsume)
	if userInfo, err := systemUserDao.First(map[string]interface{}{"user_id": userId}); err == nil {
		balanceLog.RemainAmount = userInfo.Balance
	}
	balanceLog.Remark = "创建团队扣除"
	balanceLogDao.CreateOne(balanceLog)
	return nil
}

// 是否达到创建团队条件
func (t *TeamService) IsCreateTeam(userId string) bool {
	//先判断是否打开团队功能
	var dictServe SystemDictService
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_ALL); err != nil {
		return false
	} else {
		if data.DictNumber == 0 {
			return false
		}
	}
	// 如果已有团队返回true
	var systemTeamDao dao.Common[admindao.SystemTeam]
	if team, tErr := systemTeamDao.First(map[string]interface{}{"user_id": userId}); tErr == nil {
		if team.Status == 1 { //团队长，任职中，才显示
			return true
		}
		if team.Status == 0 { //团队长，离职
			return false
		}
	}

	fmt.Printf("IsCreateTeam userId %s", userId)
	// 不是团队长
	if !t.VerifyTeamALLAndACTIVITY() {
		return false
	}
	//用户认证
	var systemUserDao dao.Common[dao.SystemUser]
	user, err := systemUserDao.First(map[string]interface{}{"user_id": userId})
	/*  创建团队不需要实名认证
	if user.IsAuthentication == ZXZ_TEAM_CLOSE {
		return errors.New("该账户未实名认证")
	}
	*/
	if err != nil {
		return false
	}
	//团队自主创建条件：历史芝草大于等于num
	if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_CREATE); err != nil {
		return false
	} else {
		//先判断余额，余额不够，在历史芝草
		if data.DictNumber > int(user.Balance) {
			var userBalanceLogService UserBalanceLogService
			historyBalance, _ := userBalanceLogService.GetHistoryBalance(userId)
			fmt.Printf("历史芝草 = %T", historyBalance)
			if data.DictNumber > int(historyBalance) {
				return false
			}
		}
	}
	//创建团队消耗芝草
	/*
		if data, err := dictServe.GetDictByCode(ZXZ_TEAM_PROFILE_CREATE_CONSUME); err != nil {
			return false
		} else {
			if int(user.Balance) < data.DictNumber {
				return false
			}
		}
	*/
	return true
}

// 是否达到创建团队条件
func (t *TeamService) DeleteTeam(teamNumber string) bool {
	var systemTeamDao dao.Common[admindao.SystemTeam]
	if team, err := systemTeamDao.First(map[string]interface{}{"team_number": teamNumber}); err != nil {
		return false
	} else {
		var systemUserDao dao.Common[dao.SystemUser]
		systemUserDao.Query = map[string]interface{}{"team_number": teamNumber}
		systemUserDao.Update(map[string]interface{}{"team_number": "zxz"})
		systemTeamDao.DeleteById(team.Id)
		return true
	}
}

// 后台导入团队
func (t *TeamService) BatchInsertTeam(teams []admindao.SystemTeam) error {
	//用户认证
	var systemUserDao dao.Common[dao.SystemUser]
	var dictServe SystemDictService
	index := -1
	for i, team := range teams {
		if team.TeamNumber == "zxz" || team.TeamNumber == "ZXZ" {
			index = i
		}
		user, err := systemUserDao.First(map[string]interface{}{"user_id": team.UserId})
		if err != nil {
			continue
		}
		if team.TeamNumber == "" {
			team.TeamNumber, _ = dictServe.GetNextTeamNumber()
		}
		team.NickName = user.NickName
		team.Level = 0
		team.TeamPeople = 0
		team.TeamPeopleHistory = 0
		team.TeamIncome = 0
		team.Status = 1
	}
	if index != -1 {
		if len(teams) == 1 {
			return nil
		} else {
			teams = append(teams[:index], teams[(index+1):]...)
		}
	}
	var systemTeamDao dao.Common[admindao.SystemTeam]
	return systemTeamDao.Create(teams).Error
}

// 每月团队有效人数自动清零
func (t *TeamService) TeamInsertHistory() error {
	var serve CommonService[admindao.SystemTeam]
	serve.Page = 1
	serve.PageSize = 1000
	for true {
		if teamList, err := serve.SelectList(); err != nil {
			break
		} else {
			var teamHistoryDao dao.Common[admindao.SystemTeamHistory]
			if len(teamList.Data) == 0 {
				break
			}
			for _, team := range teamList.Data {
				if team.TeamNumber == "zxz" {
					continue
				}
				var record admindao.SystemTeamHistory
				d, _ := time.ParseDuration("-24h")
				record.CreatedAt = time.Now().Add(d)
				record.UpdatedAt = time.Now().Add(d)
				record.TeamId = team.Id
				record.TeamNumber = team.TeamNumber
				record.UserId = team.UserId
				record.UserName = team.UserName
				record.NickName = team.NickName
				record.Level = team.Level
				record.TeamPeople = team.TeamPeople
				record.TeamIncome = team.TeamIncome
				record.TeamPermissions = team.TeamPermissions
				record.Status = team.Status
				if err := teamHistoryDao.CreateOne(record).Error; err != nil {
					return err
				} else {
					//清空团队等级，人数
					serve.Query = map[string]interface{}{"id": team.Id}
					serve.Update(map[string]interface{}{
						"level": 0, "team_people": 0, "team_income": 0})
				}
			}
			serve.Page = serve.Page + 1
		}
	}
	return nil
}
func (t *TeamService) UpdateTeamUser(userId, teamNumber string, IsEffectiveManpower, IsNotEffectiveManpower int) error {
	//用户认证
	var systemUserDao dao.Common[dao.SystemUser]
	if user, err := systemUserDao.First(map[string]interface{}{"user_id": userId}); err != nil {
		return err
	} else {
		update := map[string]interface{}{}
		teamPeople := 0
		if teamNumber != "" && teamNumber != "zxz" {
			update["team_number"] = teamNumber
		}
		if IsEffectiveManpower == 1 {
			update["is_effective_manpower"] = 1
			teamPeople = 1
		}
		if IsNotEffectiveManpower == 1 {
			update["is_effective_manpower"] = 0
			teamPeople = -1
		}
		if userErr := systemUserDao.UpdateOne(user.Id, update).Error; userErr != nil {
			return userErr
		} else {
			var dictServe SystemDictService
			result, _ := dictServe.GetValueByType(ZXZ_TEAM_LEVEL)
			var systemTeamDao dao.Common[admindao.SystemTeam]
			//如果团队和用户团队号相同，则在本团队有效人数+1或者-1
			if teamNumber == "" || teamNumber == "zxz" || user.TeamNumber == teamNumber {
				if teamPeople != 0 {
					systemTeamDao.Query = map[string]interface{}{"team_number": user.TeamNumber}
					systemTeamDao.Update(map[string]interface{}{
						"team_people":         gorm.Expr("team_people + ?", teamPeople),
						"team_people_history": gorm.Expr("team_people_history + ?", teamPeople)})
					//计算团队等级
					team, _ := systemTeamDao.First(systemTeamDao.Query)
					newTeamPeople := team.TeamPeople
					level := 0
					for i := 0; i < len(result); i++ {
						levelTemp := result[i].DictNumber
						if newTeamPeople >= levelTemp {
							val, strErr := strconv.Atoi(result[i].DictValue)
							if strErr == nil {
								level = val
							}
						}
					}
					if level != team.Level {
						systemTeamDao.Query = map[string]interface{}{"id": team.Id}
						systemTeamDao.Update(map[string]interface{}{"level": level})
					}

				}

			} else if teamNumber != "" && teamNumber != "zxz" { //如果已经调整到了别的团队
				//判断如果当前用户是有效人力，则本团队有效人数减少
				if user.IsEffectiveManpower == 1 {
					systemTeamDao.Query = map[string]interface{}{"team_number": user.TeamNumber}
					systemTeamDao.Update(map[string]interface{}{
						"team_people":         gorm.Expr("team_people - ?", 1),
						"team_people_history": gorm.Expr("team_people_history - ?", 1)})
					team, _ := systemTeamDao.First(systemTeamDao.Query)
					newTeamPeople := team.TeamPeople
					level := 0
					for i := 0; i < len(result); i++ {
						levelTemp := result[i].DictNumber
						if newTeamPeople >= levelTemp {
							val, strErr := strconv.Atoi(result[i].DictValue)
							if strErr == nil {
								level = val
							}
						}
					}
					if level != team.Level {
						systemTeamDao.Query = map[string]interface{}{"id": team.Id}
						systemTeamDao.Update(map[string]interface{}{"level": level})
					}
				}
				if teamPeople > 0 { //判断如果强制修改有效用户，才对本团队+1
					systemTeamDao.Query = map[string]interface{}{"team_number": teamNumber}
					systemTeamDao.Update(map[string]interface{}{
						"team_people":         gorm.Expr("team_people + ?", teamPeople),
						"team_people_history": gorm.Expr("team_people_history + ?", teamPeople)})
					if team, teamErr := systemTeamDao.First(systemTeamDao.Query); teamErr != nil {
						return teamErr
					} else {
						newTeamPeople := team.TeamPeople
						level := 0
						for i := 0; i < len(result); i++ {
							levelTemp := result[i].DictNumber
							if newTeamPeople >= levelTemp {
								val, strErr := strconv.Atoi(result[i].DictValue)
								if strErr == nil {
									level = val
								}
							}
						}
						if level != team.Level {
							systemTeamDao.Query = map[string]interface{}{"id": team.Id}
							systemTeamDao.Update(map[string]interface{}{"level": level})
						}
					}
				}
			}
			return nil
		}
	}
}

// 每十分钟核算团队总收入
func (t *TeamService) TeamIncomeCron() error {
	var serve CommonService[admindao.SystemTeam]
	serve.Page = 1
	serve.PageSize = 1000
	for true {
		if teamList, err := serve.SelectList(); err != nil {
			break
		} else {
			var userDao admindao.Common[admindao.SystemUser]
			if len(teamList.Data) == 0 {
				break
			}
			for _, team := range teamList.Data {
				if team.TeamNumber == "zxz" {
					continue
				}
				/*countSql := fmt.Sprintf(
					"select cast(SUM(balance) as signed) as total from tas_system_user where team_number = '%v'",
					team.TeamNumber,
				)*/
				countSql := fmt.Sprintf("SELECT cast(SUM(amount) as signed) as total FROM tas_system_user_balance_log WHERE team_number = '%v' AND LEFT (created_at,7) = DATE_FORMAT(CURDATE(), '%%Y-%%m') AND log_type = 1",
					team.TeamNumber,
				)
				total, err := userDao.RawCount(countSql, "total")
				if err == nil {
					serve.Query = map[string]interface{}{"id": team.Id}
					serve.Update(map[string]interface{}{"team_income": total})
				}
			}
			serve.Page = serve.Page + 1
		}
	}
	return nil
}

func (t *TeamService) QueryTeamIncomeSetting(page, pageSize int64) (int64, []admindao.SystemTeamIncomeSetting, error) {
	var serve CommonService[admindao.SystemTeamIncomeSetting]
	serve.Page = page
	serve.PageSize = pageSize
	if tisList, err := serve.SelectList(); err != nil {
		return 0, nil, err
	} else {
		return tisList.Total, tisList.Data, nil
	}
}

func (t *TeamService) QueryTeamIncomeSettingByProjectIdAndLevel(projectId string, level int64) ([]admindao.SystemTeamIncomeSetting, error) {
	var serve CommonService[admindao.SystemTeamIncomeSetting]
	serve.Query = map[string]interface{}{
		"project_id": projectId,
		"level":      level}
	return serve.FindAll()
}
func (t *TeamService) UpdateTeamIncomeSetting(id uint, projectId, title string, incomeType, level int, incomeNumber float64) error {
	var serve dao.Common[admindao.SystemTeamIncomeSetting]
	set := map[string]interface{}{
		"project_id":    projectId,
		"title":         title,
		"income_type":   incomeType,
		"level":         level,
		"income_number": incomeNumber}
	return serve.UpdateOne(id, set).Error
}

func (t *TeamService) BatchInsertTeamIncomeSetting(teamIncomeSetting []admindao.SystemTeamIncomeSetting) error {
	var serve admindao.Common[admindao.SystemTeamIncomeSetting]
	//清理，覆盖
	serve.Truncate("tas_system_team_income_setting")
	pageSize := 1000
	//小于1000条直接新增
	if len(teamIncomeSetting) < pageSize {
		return serve.Create(teamIncomeSetting).Error
	} else { //大于1000条分批新增
		teamLength := len(teamIncomeSetting) / pageSize
		for i := 0; i < teamLength; i++ {
			slice := teamIncomeSetting[i*pageSize : (i*pageSize)+pageSize]
			return serve.Create(slice).Error
		}
		//剩余条数
		if len(teamIncomeSetting)-(teamLength*pageSize) > 0 {
			slice := teamIncomeSetting[teamLength*pageSize:]
			return serve.Create(slice).Error
		}
	}
	return nil
}

func (s *TeamService) VerifyTeamNumber(teamNumber string) (bool, error) {
	var serve CommonService[admindao.SystemTeam]
	serve.Query = map[string]interface{}{"team_number": teamNumber}
	if count, err := serve.Count(); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

type SystemTeam struct {
	admindao.SystemTeam
	LastMonthLevel       string `json:"last_month_level"`        //上月团队等级
	NowMonth             string `json:"now_month"`               //当前月份
	NowInviteProgress    string `json:"now_invite_progress"`     //本月邀请进度
	TlPhone              string `json:"tl_phone"`                //团长手机号
	TlEmail              string `json:"tl_email"`                //团长邮箱
	NowInvitePeople      int    `json:"now_invite_people"`       //本月邀请人数
	NowInviteProgressNew string `json:"now_invite_progress_new"` //本月邀请进度新-如果已经满级这个字段就会出现数值
}

func (t *TeamService) QueryTeamPage(userName, teamNumber, userId, status, teamIncome, level string, page, pageSize int64, teamPeople, teamPeopleHistory uint) (int64, []SystemTeam, error) {
	var commonServe CommonService[SystemTeam]
	commonServe.Page = page
	commonServe.PageSize = pageSize
	if utils.StringIsNotEmpty(userName) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.user_name LIKE '%%%v%%'", userName))
	}
	if utils.StringIsNotEmpty(teamNumber) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.team_number LIKE '%%%v%%'", teamNumber))
	}
	if utils.StringIsNotEmpty(userId) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.user_id LIKE '%%%v%%'", userId))
	}
	if utils.StringIsNotEmpty(status) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.status = '%v'", status))
	}
	if utils.StringIsNotEmpty(teamIncome) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.team_income = '%v'", teamIncome))
	}
	if utils.StringIsNotEmpty(level) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.level = '%v'", level))
	}
	if teamPeople > 0 {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.team_people = '%v'", teamPeople))
	}
	if teamPeopleHistory > 0 {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.team_people_history = '%v'", teamPeopleHistory))
	}
	commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.team_number != 'zxz'"))
	field := fmt.Sprintf("tas_system_team.*,tas_system_team_history.level last_month_level,left(now(),7) now_month,CONCAT(tas_system_team.team_people,'/',tas_system_dict.dict_number) now_invite_progress,d.dict_number now_invite_progress_new,tas_system_user.phone tl_phone,tas_system_user.email tl_email")
	commonServe.SelectField = &field
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_team_history on tas_system_team.id = tas_system_team_history.team_id and left(tas_system_team_history.created_at,7) = DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 MONTH), '%%Y-%%m') "))
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_dict on tas_system_team.level+1 = tas_system_dict.dict_value and tas_system_dict.dict_type = 'ZXZ_TEAM_LEVEL'"))
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_dict d on tas_system_team.level = d.dict_value and d.dict_type = 'ZXZ_TEAM_LEVEL'"))
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_user on tas_system_team.user_id = tas_system_user.user_id"))
	commonServe.Order = "tas_system_team.id asc"
	if res, err := commonServe.SelectList(); err != nil {
		return 0, nil, err
	} else {
		return res.Total, res.Data, nil
	}
}

func (s *TeamService) FindAllTeamNumber() ([]string, error) {
	var serve admindao.Common[admindao.SystemTeam]
	sql := fmt.Sprintf("SELECT DISTINCT team_number from tas_system_team WHERE `status` = %d", STATUS_NORMAL)
	list, err := serve.RawList(sql)
	if err != nil {
		return nil, err
	}
	var res = []string{}
	for _, team := range list {
		res = append(res, team.TeamNumber)
	}
	return res, nil
}

func (t *TeamService) EditTeamInfo(id, status uint, teamPermissions string) error {
	var commonServe admindao.Common[admindao.SystemTeam]
	_, err := commonServe.First(map[string]interface{}{"id": id})
	if err != nil {
		return errors.New("该团队不存在")
	}
	set := map[string]interface{}{}
	if utils.StringIsNotEmpty(teamPermissions) {
		set["team_permissions"] = teamPermissions
	}
	if utils.StringIsNotEmpty(utils.UintToString(status)) {
		set["status"] = status
	}
	return commonServe.UpdateOne(id, set).Error
}

type SystemTeamHistory struct {
	admindao.SystemTeamHistory
	PeopleAndLevel string `json:"people_and_level"`
}

func (t *TeamService) QueryHistoryPeopleAndLevel(id uint) ([]string, error) {
	var commonServe admindao.Common[SystemTeamHistory]
	sql := fmt.Sprintf("select CONCAT(left(created_at,4),'年',substring(created_at,6,2),'月 : ',`level`,'级, ',team_people,'人') people_and_level from tas_system_team_history WHERE `team_id` = %d order by created_at desc", id)
	if list, err := commonServe.RawList(sql); err != nil {
		return nil, err
	} else {
		var res []string
		for _, teamHistory := range list {
			res = append(res, teamHistory.PeopleAndLevel)
		}
		return res, nil
	}
}

func (t *TeamService) QueryTeamInfo(userId string) (*SystemTeam, error) {
	var commonServe admindao.Common[SystemTeam]
	sql := fmt.Sprintf("select tas_system_team.*,tas_system_team_history.level last_month_level,left(now(),7) now_month,CONCAT(tas_system_team.team_people,'/',tas_system_dict.dict_number) now_invite_progress from tas_system_team ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_team_history on tas_system_team.id = tas_system_team_history.team_id and left(tas_system_team_history.created_at,7) = DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 MONTH), '%%Y-%%m') ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_dict on tas_system_team.level+1 = tas_system_dict.dict_value and tas_system_dict.dict_type = 'ZXZ_TEAM_LEVEL' ")
	sql += fmt.Sprintf("where tas_system_team.user_id = '%v' and tas_system_team.team_number != 'zxz'", userId)
	if team, err := commonServe.RawOne(sql); err != nil {
		return nil, err
	} else {
		var userServe admindao.Common[SystemUser]
		sql := fmt.Sprintf("SELECT * from tas_system_user WHERE team_number = '%v' and DATE_FORMAT(created_at,'%%Y%%m')=DATE_FORMAT(CURDATE(),'%%Y%%m')", team.TeamNumber)
		if list, err := userServe.RawList(sql); err != nil {
			return nil, err
		} else {
			team.NowInvitePeople = len(list)
		}
		return &team, nil
	}
}

type SystemUser struct {
	admindao.SystemUser
	LastBalanceDay string `json:"last_balance_day"`
	Amount         string `json:"amount"`
	Remark         string `json:"remark"`
}

func (t *TeamService) QueryTeamManagePage(userId, teamNumber, realName, lastBalanceStart, lastBalanceEnd, createdAtStart, createdAtEnd, amountFrom, amountTo, balanceFrom, balanceTo, auth string, page, pageSize int64) (int64, []SystemUser, error) {
	var commonServe CommonService[SystemUser]
	commonServe.Page = page
	commonServe.PageSize = pageSize

	if utils.StringIsNotEmpty(teamNumber) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_user.team_number = '%v' ", teamNumber))
	}
	if utils.StringIsNotEmpty(realName) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_user.real_name like '%%%v%%' ", realName))
	}
	if utils.StringIsNotEmpty(userId) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_user.user_id like '%%%v%%' ", userId))
	}
	if utils.StringIsNotEmpty(lastBalanceStart) && utils.StringIsNotEmpty(lastBalanceEnd) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("left(tas_system_user.last_balance_day,10) >= '%v' and left(last_balance_day,10) <= '%v' ", lastBalanceStart, lastBalanceEnd))
	}
	if utils.StringIsNotEmpty(createdAtStart) && utils.StringIsNotEmpty(createdAtEnd) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("left(tas_system_user.created_at,10) >= '%v' and left(last_balance_day,10) <= '%v' ", createdAtStart, createdAtEnd))
	}
	if utils.StringIsNotEmpty(amountFrom) && utils.StringIsNotEmpty(amountTo) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_user_balance_log.amount >= %v and tas_system_user_balance_log.amount <= %v ", amountFrom, amountTo))
	}
	if utils.StringIsNotEmpty(balanceFrom) && utils.StringIsNotEmpty(balanceTo) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_user.balance >= %v and tas_system_user.balance <= %v ", balanceFrom, balanceTo))
	}
	if utils.StringIsNotEmpty(auth) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_user.id in (SELECT DISTINCT(system_user_id) from tas_system_user_restriction WHERE project_id = '%v') ", auth))
	}
	//field := fmt.Sprintf("tas_system_user.id,tas_system_user.balance,tas_system_user_balance_log.last_balance_day,tas_system_user_balance_log.amount,tas_system_user.user_id,tas_system_user.real_name,tas_system_user.nick_name,tas_system_user.phone,tas_system_user.alipay_account,tas_system_user.created_at,tas_system_user.team_activation_date,tas_system_user_balance_log.remark ")
	field := fmt.Sprintf("tas_system_user.*,tas_system_user_balance_log.last_balance_day,tas_system_user_balance_log.amount,tas_system_user_balance_log.remark ")
	commonServe.SelectField = &field
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN (select user_id,max(created_at) last_balance_day,amount,remark from tas_system_user_balance_log WHERE log_type = 1 GROUP BY user_id ) tas_system_user_balance_log on tas_system_user.user_id = tas_system_user_balance_log.user_id "))
	if res, err := commonServe.SelectList(); err != nil {
		return 0, nil, err
	} else {
		return res.Total, res.Data, nil
	}
}

func (t *TeamService) GetTeamOne(teamNumber string) (admindao.SystemTeam, error) {
	var systemTeamDao CommonService[admindao.SystemTeam]
	systemTeamDao.Query = map[string]interface{}{"team_number": teamNumber}
	return systemTeamDao.First()
}

type TeamIncomeResponse struct {
	Amount string `json:"amount"`
	Source string `json:"source"`
	UserId string `json:"user_id"`
	//RealName string `json:"real_name"`
	NickName string `json:"nick_name"`
}

func (t *TeamService) GetTeamIncomeList(teamNumber, yearMonth string, page, pageSize int64) (int64, []TeamIncomeResponse, error) {
	var teamIncome admindao.Common[TeamIncomeResponse]
	tlsql := fmt.Sprintf("select d.nick_name,d.user_id,c.amount,c.source from tas_system_user d LEFT JOIN ")
	tlsql += fmt.Sprintf("(SELECT sum(b.amount) amount,GROUP_CONCAT(b.amount separator '+') source,b.user_id from (SELECT IFNULL(sum( amount ),0) amount,(SELECT user_id FROM tas_system_team WHERE team_number = '%v') user_id from tas_system_user_balance_log WHERE log_type = 1 and user_id = (select user_id from tas_system_team WHERE team_number = '%v') and business_type = 3 and left(created_at,7) = '%v' UNION ALL SELECT IFNULL(sum( amount ),0) amount,(SELECT user_id FROM tas_system_team WHERE team_number = '%v') user_id from tas_system_user_balance_log WHERE log_type = 1 and user_id = (select user_id from tas_system_team WHERE team_number = '%v') and business_type = 4 and left(created_at,7) = '%v') b ) c ", teamNumber, teamNumber, yearMonth, teamNumber, teamNumber, yearMonth)
	tlsql += fmt.Sprintf("on d.user_id = c.user_id WHERE d.user_id = (select user_id from tas_system_team WHERE team_number = '%v') ", teamNumber)
	//sql += fmt.Sprintf("UNION ALL ")
	sql := fmt.Sprintf("SELECT e.nick_name,e.user_id,f.amount,f.source from tas_system_user e ")
	sql += fmt.Sprintf("LEFT JOIN (SELECT sum( amount ) amount,'' source,user_id FROM tas_system_user_balance_log WHERE log_type = 1 AND user_id != ( SELECT user_id FROM tas_system_team WHERE team_number = '%v' ) AND team_number = '%v' AND business_type = 3 AND LEFT ( created_at, 7 ) = '%v' GROUP BY user_id) f ON e.user_id = f.user_id WHERE e.team_number = '%v' ORDER BY f.amount desc %v ", teamNumber, teamNumber, yearMonth, teamNumber, utils.Limit(page, pageSize))

	//countSql := fmt.Sprintf("select count(1) total from (select d.nick_name,d.user_id,c.amount,c.source from tas_system_user d LEFT JOIN ")
	//countSql += fmt.Sprintf("(SELECT sum(b.amount) amount,GROUP_CONCAT(b.amount separator '+') source,b.user_id from (SELECT sum(amount) amount,user_id from tas_system_user_balance_log WHERE log_type = 1 and user_id = (select user_id from tas_system_team WHERE team_number = '%v') and business_type = 3 and left(created_at,7) = '%v' UNION ALL SELECT sum(amount) amount,user_id from tas_system_user_balance_log WHERE log_type = 1 and user_id = (select user_id from tas_system_team WHERE team_number = '%v') and business_type = 4 and left(created_at,7) = '%v') b ) c ", teamNumber, yearMonth, teamNumber, yearMonth)
	//countSql += fmt.Sprintf("on d.user_id = c.user_id WHERE d.user_id = (select user_id from tas_system_team WHERE team_number = '%v') ", teamNumber)
	//countSql += fmt.Sprintf("UNION ALL ")
	countSql := fmt.Sprintf("SELECT count(1) total from tas_system_user e ")
	countSql += fmt.Sprintf("LEFT JOIN (SELECT sum( amount ) amount,'' source,user_id FROM tas_system_user_balance_log WHERE log_type = 1 AND user_id != ( SELECT user_id FROM tas_system_team WHERE team_number = '%v' ) AND team_number = '%v' AND business_type = 3 AND LEFT ( created_at, 7 ) = '%v' GROUP BY user_id ) f ON e.user_id = f.user_id WHERE e.team_number = '%v' ", teamNumber, teamNumber, yearMonth, teamNumber)
	total, err := teamIncome.RawCount(countSql, "total")
	if err != nil {
		return 0, nil, err
	}
	listTl, err := teamIncome.RawList(tlsql)
	if err != nil {
		return 0, nil, err
	}
	list, err := teamIncome.RawList(sql)
	if err != nil {
		return 0, nil, err
	}
	listTl = append(listTl, list...)
	return total, listTl, nil
}

type TeamSumIncomeThisMonthResponse struct {
	SumAmount string `json:"sum_amount"`
}

func (t *TeamService) GetTeamSumIncomeThisMonth(teamNumber string) (*TeamSumIncomeThisMonthResponse, error) {
	var common admindao.Common[TeamSumIncomeThisMonthResponse]
	sql := fmt.Sprintf("SELECT sum(a.amount) sum_amount from (select sum(amount) amount from tas_system_user_balance_log WHERE log_type = 1 and user_id = (select user_id from tas_system_team WHERE team_number = '%v') and left(created_at,7) = DATE_FORMAT(CURDATE(), '%%Y-%%m') and business_type in (3,4) union all select sum(amount) amount from tas_system_user_balance_log WHERE log_type = 1 and user_id in (select user_id from tas_system_user WHERE team_number = '%v') and left(created_at,7) = DATE_FORMAT(CURDATE(), '%%Y-%%m') and business_type = 3 )a", teamNumber, teamNumber)
	amount, err := common.RawOne(sql)
	if err != nil {
		return nil, err
	}
	return &amount, nil
}

type ExportTeamMemberIncomeByCountResponse struct {
	UserId              string    `json:"user_id"`
	RealName            string    `json:"real_name"`
	NickName            string    `json:"nick_name"`
	Phone               string    `json:"phone"`
	Email               string    `json:"email"`
	AlipayAccount       string    `json:"alipay_account"`
	IncomeTime          time.Time `json:"income_time"`
	Amount              string    `json:"amount"`
	RemainAmount        string    `json:"remain_amount"`
	JoinTeamDate        time.Time `json:"join_team_date"`
	TeamActivationDate  string    `json:"team_activation_date"`
	IsEffectiveManpower string    `json:"is_effective_manpower"`
	TlUserId            string    `json:"tl_user_id"`
	TlRealName          string    `json:"tl_real_name"`
	TlNickName          string    `json:"tl_nick_name"`
	TlPhone             string    `json:"tl_phone"`
	TlEmail             string    `json:"tl_email"`
	TeamNumber          string    `json:"team_number"`
	Level               string    `json:"level"`
}

func (t *TeamService) ExportTeamMemberIncomeByCount(teamNumber, incomeDateStart, incomeDateEnd, joinDateStart, joinDateEnd string) ([]ExportTeamMemberIncomeByCountResponse, error) {
	var common admindao.Common[ExportTeamMemberIncomeByCountResponse]
	sql := fmt.Sprintf("SELECT a.id,b.user_id,b.real_name,b.nick_name,b.phone,")
	sql += fmt.Sprintf("b.email,b.alipay_account,a.created_at income_time,")
	sql += fmt.Sprintf("a.amount,a.remain_amount,b.created_at join_team_date,")
	sql += fmt.Sprintf("b.team_activation_date,b.is_effective_manpower,c.user_id tl_user_id,")
	sql += fmt.Sprintf("d.real_name tl_real_name,c.nick_name tl_nick_name,d.phone tl_phone,")
	sql += fmt.Sprintf("d.email tl_email,c.team_number,c.level ")
	sql += fmt.Sprintf("from tas_system_user_balance_log a ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_user b on a.user_id = b.user_id ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_team c on b.team_number = c.team_number ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_user d on c.user_id = d.user_id ")
	sql += fmt.Sprintf("where log_type = 1 and business_type in (3,4) ")
	sql += fmt.Sprintf("and a.team_number = '%v'", teamNumber)
	if utils.StringIsNotEmpty(incomeDateStart) && utils.StringIsNotEmpty(incomeDateEnd) {
		sql += fmt.Sprintf("and left(a.created_at,10) >= '%v' and left(a.created_at,10) <= '%v'", incomeDateStart, incomeDateEnd)
	}
	if utils.StringIsNotEmpty(joinDateStart) && utils.StringIsNotEmpty(joinDateEnd) {
		sql += fmt.Sprintf("and left(b.created_at,10) >= '%v' and left(b.created_at,10) <= '%v'", joinDateStart, joinDateEnd)
	}

	list, err := common.RawList(sql)
	if err != nil {
		return nil, err
	}
	return list, err
}

type ExportTeamMemberIncomeBySumResponse struct {
	UserId              string    `json:"user_id"`
	RealName            string    `json:"real_name"`
	NickName            string    `json:"nick_name"`
	Phone               string    `json:"phone"`
	Email               string    `json:"email"`
	AlipayAccount       string    `json:"alipay_account"`
	Amount              string    `json:"amount"`
	RemainAmount        string    `json:"remain_amount"`
	JoinTeamDate        time.Time `json:"join_team_date"`
	TeamActivationDate  string    `json:"team_activation_date"`
	IsEffectiveManpower string    `json:"is_effective_manpower"`
	TlUserId            string    `json:"tl_user_id"`
	TlRealName          string    `json:"tl_real_name"`
	TlNickName          string    `json:"tl_nick_name"`
	TlPhone             string    `json:"tl_phone"`
	TlEmail             string    `json:"tl_email"`
	TeamNumber          string    `json:"team_number"`
	Level               string    `json:"level"`
}

func (t *TeamService) ExportTeamMemberIncomeBySum(teamNumber, incomeDateStart, incomeDateEnd, joinDateStart, joinDateEnd string) ([]ExportTeamMemberIncomeBySumResponse, error) {
	var common admindao.Common[ExportTeamMemberIncomeBySumResponse]
	sql := fmt.Sprintf("SELECT a.user_id,a.real_name,a.nick_name,a.phone,")
	sql += fmt.Sprintf("a.email,a.alipay_account,IFNULL(b.sum_amount,0) amount,")
	sql += fmt.Sprintf("a.balance remain_amount,a.created_at join_team_date,a.team_activation_date,")
	sql += fmt.Sprintf("a.is_effective_manpower,c.user_id tl_user_id,d.real_name tl_real_name,")
	sql += fmt.Sprintf("c.nick_name tl_nick_name,d.phone tl_phone,d.email tl_email,c.team_number,c.level ")
	sql += fmt.Sprintf("from tas_system_user a ")
	sql += fmt.Sprintf("LEFT JOIN (SELECT sum(amount) sum_amount,user_id from tas_system_user_balance_log ")
	sql += fmt.Sprintf("WHERE log_type = 1 and business_type in (3,4) ")
	if utils.StringIsNotEmpty(incomeDateStart) && utils.StringIsNotEmpty(incomeDateEnd) {
		sql += fmt.Sprintf("and left(created_at,10) >= '%v' and left(created_at,10) <= '%v'", incomeDateStart, incomeDateEnd)
	}
	sql += fmt.Sprintf("GROUP BY user_id) b on a.user_id = b.user_id ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_team c on a.team_number = c.team_number ")
	sql += fmt.Sprintf("LEFT JOIN tas_system_user d on c.user_id = d.user_id ")
	sql += fmt.Sprintf("WHERE a.team_number = '%v' ", teamNumber)
	if utils.StringIsNotEmpty(joinDateStart) && utils.StringIsNotEmpty(joinDateEnd) {
		sql += fmt.Sprintf("and left(a.created_at,10) >= '%v' and left(a.created_at,10) <= '%v'", joinDateStart, joinDateEnd)
	}

	list, err := common.RawList(sql)
	if err != nil {
		return nil, err
	}
	return list, err
}

func (t *TeamService) QuerySystemUserRestriction(userId uint) ([]admindao.SystemUserRestriction, error) {
	var commonServe CommonService[admindao.SystemUserRestriction]
	commonServe.Query = map[string]interface{}{"system_user_id": userId}
	return commonServe.FindAll()
}
func (t *TeamService) TeamMaxLevel(teamNumber string) int64 {
	var teamDao admindao.Common[admindao.SystemTeam]
	countSql := fmt.Sprintf(
		"select GREATEST(t.`level`,max(IFNULL(h.`level`,0))) as total from tas_system_team t LEFT JOIN (select * from tas_system_team_history where created_at >= date_add(curdate()- DAY (curdate())+ 1,INTERVAL - 1 MONTH)) h ON t.team_number = h.team_number where t.team_number = '%v'",
		teamNumber,
	)
	levelMax, err := teamDao.RawCount(countSql, "total")
	if err != nil {
		return 0
	} else {
		return levelMax
	}
}

func (t *TeamService) GetTeamInviteUrl() (*admindao.SystemDict, error) {
	var dictServe SystemDictService
	//实名认证是否开启
	if data, err := dictServe.GetDictByCode(REGIST_URL); err != nil {
		fmt.Printf("REGIST_URL 字典不存在")
		return nil, err
	} else {
		//实名认证开启并且用户未实名
		return &data, err
	}
}

func (t *TeamService) QueryUserIsTeamLeader(userId string) (res bool, err error) {
	var teamDao admindao.Common[admindao.SystemTeam]
	sql := fmt.Sprintf("select count(1) total from tas_system_team where user_id = '%v' and team_number != 'zxz' ", userId)
	if count, err := teamDao.RawCount(sql, "total"); err != nil {
		return false, err
	} else {
		if count > 0 {
			return true, err
		} else {
			return false, err
		}
	}
}

func (t *TeamService) TeamImportUpdate(teams []admindao.SystemTeam, users []admindao.SystemUser) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var teamDao admindao.Common[admindao.SystemTeam]
		teamDao.Tx = tx
		for _, team := range teams {
			if err := tx.Model(team).Where("user_id = ?", team.UserId).Updates(team).Error; err != nil {
				return err
			}
		}

		for _, user := range users {
			if err := tx.Model(user).Where("user_id = ?", user.UserId).Updates(user).Error; err != nil {
				return err
			}
		}
		return nil
	})
}

type ExportTeamResponse struct {
	Id                uint    `json:"id"`
	UserId            string  `json:"user_id"`             //团长用户id
	UserName          string  `json:"user_name"`           //团长用户姓名
	NickName          string  `json:"nick_name"`           //团长用户昵称
	TlPhone           string  `json:"tl_phone"`            //团长手机号
	TlEmail           string  `json:"tl_email"`            //团长邮箱
	TeamNumber        string  `json:"team_number"`         //团队编号
	Level             int     `json:"level"`               //团队等级
	NowInviteProgress string  `json:"now_invite_progress"` //本月邀请进度
	NowMonth          string  `json:"now_month"`           //当前月份
	LastMonthLevel    string  `json:"last_month_level"`    //上月团队等级
	PeopleAndLevel    string  `json:"people_and_level"`
	TeamPeopleHistory int     `json:"team_people_history"` //团队历史人数
	TlUrl             string  `json:"tl_url"`
	TeamIncome        float64 `json:"team_income"`      //团队本月收入
	Status            int     `json:"status"`           //0 注销;1 任职中; 2 已离职
	TeamPermissions   string  `json:"team_permissions"` //团队项目可见配置
}

func (ExportTeamResponse) TableName() string {
	return "tas_system_team"
}
func (t *TeamService) ExportTeamInfo(ids []uint) ([]ExportTeamResponse, error) {
	var commonServe CommonService[ExportTeamResponse]
	commonServe.PageSize = -1
	if len(ids) > 0 {
		queryIds := make([]string, len(ids))
		for i, id := range ids {
			queryIds[i] = utils.UintToString(id)
		}
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.id in (%v)", strings.Join(queryIds, ",")))
	}
	commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("tas_system_team.team_number != 'zxz'"))
	field := fmt.Sprintf("tas_system_team.*,tas_system_team_history.level last_month_level,left(now(),7) now_month,CONCAT(tas_system_team.team_people,'/',tas_system_dict.dict_number) now_invite_progress,tas_system_user.phone tl_phone,tas_system_user.email tl_email")
	commonServe.SelectField = &field
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_team_history on tas_system_team.id = tas_system_team_history.team_id and left(tas_system_team_history.created_at,7) = DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 MONTH), '%%Y-%%m') "))
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_dict on tas_system_team.level = tas_system_dict.dict_value and tas_system_dict.dict_type = 'ZXZ_TEAM_LEVEL'"))
	commonServe.LeftJoin = append(commonServe.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_user on tas_system_team.user_id = tas_system_user.user_id"))
	if res, err := commonServe.SelectList(); err != nil {
		return nil, err
	} else {
		var commonServe admindao.Common[SystemTeamHistory]
		for i, team := range res.Data {
			sql := fmt.Sprintf("select CONCAT(left(created_at,4),'年',substring(created_at,4,1),'月 : ',`level`,'级, ',team_people,'人') people_and_level from tas_system_team_history WHERE `team_id` = %d order by created_at desc", team.Id)
			if list, err := commonServe.RawList(sql); err != nil {
				return nil, err
			} else {
				peopleAndLevel := ""
				for _, teamHistory := range list {
					peopleAndLevel += teamHistory.PeopleAndLevel + "; "
				}
				res.Data[i].PeopleAndLevel = peopleAndLevel
			}
		}
		return res.Data, nil
	}
}

func (t *TeamService) ExcelTeamInfoModify(teams []admindao.SystemTeam) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var teamDao admindao.Common[admindao.SystemTeam]
		var systemUserDao dao.Common[dao.SystemUser]
		teamDao.Tx = tx
		for _, team := range teams {
			//删除团队
			if team.Status == 2 {
				systemUserDao.Query = map[string]interface{}{"team_number": team.TeamNumber}
				systemUserDao.Update(map[string]interface{}{"team_number": "zxz"})
				teamDao.DeleteByStringColumn("team_number", team.TeamNumber)
			} else {
				teamDao.Query = map[string]interface{}{"team_number": team.TeamNumber}
				update := map[string]interface{}{}
				update["status"] = team.Status
				//if utils.StringIsNotEmpty(team.TeamPermissions) {
				update["team_permissions"] = team.TeamPermissions
				//}
				if err := teamDao.Update(update).Error; err != nil {
					return err
				}
				/*if err := tx.Model(team).Where("team_number = ?", team.TeamNumber).Updates(team).Error; err != nil {
					return err
				}*/
			}
		}
		return nil
	})
}

func (t *TeamService) ExcelTeamHistoryLevelModify(teams []admindao.SystemTeam) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var teamDao admindao.Common[admindao.SystemTeam]
		var systemUserDao dao.Common[dao.SystemUser]
		teamDao.Tx = tx
		for _, team := range teams {
			//删除团队
			if team.Status == 2 {
				systemUserDao.Query = map[string]interface{}{"team_number": team.TeamNumber}
				systemUserDao.Update(map[string]interface{}{"team_number": "zxz"})
				teamDao.DeleteByStringColumn("team_number", team.TeamNumber)
			} else {
				if err := tx.Model(team).Where("team_number = ?", team.TeamNumber).Updates(team).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})
}
